﻿Imports Entities
Imports Business
Imports DataAccess
Public Class MantencionClientes
    Private _Cliente As New clientes
    Private _Calle As New calles

    Private _ClientesList As New List(Of clientes)
    Private _CallesList As New List(Of calles)
    Private _VillasList As New List(Of villas)
    Private _ClientesP As New List(Of ClientesP)

    Private Sub MantencionClientes_Activated(sender As Object, e As EventArgs) Handles Me.Activated

        TituloCombos()
        TituloGrid()
        cVillas.Focus()
    End Sub

  

#Region "Métodos Privados"

    Private Sub TituloCombos()
        _ClientesList = ClienteBL.List
        _VillasList = VillaBL.List
        With cVillas
            .DataSource = _VillasList
            .ValueMember = "VILLA"
            .DisplayMember = "NOMBRE"
        End With
    End Sub

    Private Sub TituloCalle()
        If Not IsNothing(_CallesList) AndAlso _CallesList.Count > 0 Then
            With lsCalles
                .DataSource = _CallesList
                .ValueMember = "CALLE"
                .DisplayMember = "NOMBRE"
            End With
        Else
            tCalle.Clear()
            lsCalles.DataSource = Nothing
        End If

    End Sub

    Private Sub TituloGrid()
        With gClientes
            _ClientesP = ClienteBL.ListP
            If IsNothing(_ClientesP) Then Exit Sub
            .DataSource = _ClientesP
            Dim ButtonCell As DataGridViewButtonCell = New DataGridViewButtonCell
            ButtonCell.UseColumnTextForButtonValue = True
            Dim ColumnaHistorial As New DataGridViewButtonColumn

            With ColumnaHistorial

                .HeaderText = "Ver Historial"
                .Name = "Historial"
                .ReadOnly = False
                '.ValueType = Type.GetType("System.Int64")
                .Resizable = False
                .CellTemplate = ButtonCell

                ButtonCell.UseColumnTextForButtonValue = True

            End With

            If Not .Columns.Contains("Historial") Then
                .Columns.Add(ColumnaHistorial)
            End If
            Dim sumaAncho As Long = 0
            For Each col As DataGridViewColumn In gClientes.Columns
                col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
                sumaAncho += col.Width
            Next
            .Width = sumaAncho
            'ESTABLECE LA FUENTE Y EL ANCHO
            .Font = New Drawing.Font("Tahoma", Util.GridFont, FontStyle.Regular, GraphicsUnit.Point)

            .Columns("ClienteId").Visible = False

            .RowHeadersVisible = False
            'ESTABLECE LA ALINEACION DE LOS ENCABEZADOS
            For Each columna As DataGridViewColumn In gClientes.Columns
                columna.HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter
            Next

            'ESTABLECE LA ALINEACION DEL CONTENIDO
            '.Columns(T_CALLE).DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomLeft
            '.Columns(T_VILLA).DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
        End With
    End Sub

    Private Sub Limpiar()
        bGuardar.Text = "Guardar"
        _ClientesList = Nothing
        cVillas.SelectedIndex = -1
        lsCalles.DataSource = Nothing
        tCalle.Clear()
        tNumero.Clear()
        tRut.Clear()
        tNombre.Clear()
        tFono.Clear()
    End Sub

    Private Sub cargarCliente()

        If Not IsNothing(_Cliente) Then
            tRut.Text = _Cliente.RUT
            tNumero.Text = _Cliente.NUMERO
            tNombre.Text = _Cliente.NOMBRE
            tFono.Text = _Cliente.FONO
            cVillas.SelectedValue = _Calle.VILLA
            lsCalles.SelectedValue = _Calle.CALLE
            bGuardar.Text = "Modificar"
        Else
            'tNumero.Clear()
            tRut.Clear()
            tNombre.Clear()
            tFono.Clear()
            bGuardar.Text = "Guardar"
        End If
    End Sub
#End Region

#Region "Métodos Públicos"

#End Region

#Region "Eventos Click"

    Private Sub bCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCancelar.Click
        Me.Dispose()
    End Sub

    Private Sub bGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bGuardar.Click
        If Not IsNumeric(cVillas.SelectedValue) And cVillas.SelectedValue < 1 Then
            Util.Mensaje("Debe Seleccionar Villa")
            cVillas.Focus()
            Exit Sub
        End If
        If Not IsNumeric(lsCalles.SelectedValue) And lsCalles.SelectedValue < 1 Then
            Util.Mensaje("Debe Seleccionar Calle")
            lsCalles.Focus()
            Exit Sub
        End If
        If tNumero.TextLength = 0 Then
            tNumero.Focus()
            Exit Sub
        End If
        If tRut.Text <> "  .   .   -" Then
            If Not Util.ValidaRut(tRut.Text) Then
                Util.Mensaje("El Rut Ingresado no es Correcto")
                tRut.Focus()
                Exit Sub
            End If
        End If

        Dim cliente As New clientes

        With cliente
            If Not IsNothing(_Cliente) Then .CLIENTE = _Cliente.CLIENTE
            .CALLE = lsCalles.SelectedValue
            .NUMERO = tNumero.Text.Trim.ToUpper
            .RUT = tRut.Text
            .NOMBRE = tNombre.Text.Trim.ToUpper
            .FONO = tFono.Text.Trim.ToUpper
            .ACTIVO = True
        End With

        If Not IsNothing(ClienteBL.Save(cliente)) Then
            Debug.Print(Me.Name + " cliente.CLIENTE= " + cliente.CLIENTE.ToString)
            Util.Mensaje("Cliente Guardado correctamente")

        Else
            Util.MensajeError("Error al Guardar Cliente")
        End If

        TituloGrid()
        TituloCalle()
        cVillas.Focus()
        Limpiar()
    End Sub

    Private Sub gClientes_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gClientes.Click
        If gClientes.Rows.IndexOf(gClientes.CurrentRow) >= 0 Then
            _Cliente = ClienteBL.SearchById(gClientes.Item("ClienteId", gClientes.Rows.IndexOf(gClientes.CurrentRow)).Value)
            _Calle = CalleBL.SearchById(_Cliente.CALLE)
            cargarCliente()
        End If
        If gClientes.CurrentCell.OwningColumn.Name = "Historial" Then
            Using Form As New HistorialClientes(gClientes.Item("ClienteId", gClientes.CurrentRow.Index).Value)
                Form.ShowDialog()
            End Using
        End If
    End Sub

    Private Sub bLimpiar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles bLimpiar.Click
        Limpiar()
    End Sub

#End Region
   
#Region "Eventos Change"

    Private Sub cVillas_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cVillas.SelectedIndexChanged
        If IsNumeric(cVillas.SelectedValue) AndAlso cVillas.SelectedValue > 0 Then
            _CallesList = CalleBL.ListByVillaId(cVillas.SelectedValue)
            TituloCalle()
        End If
    End Sub

    Private Sub lsCalles_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lsCalles.SelectedIndexChanged
        If lsCalles.SelectedIndex > -1 And IsNumeric(lsCalles.SelectedValue) And cVillas.SelectedIndex > -1 Then
            _ClientesList = ClienteBL.ListByCalleId(lsCalles.SelectedValue)
            _Calle = _CallesList.Where(Function(c) c.CALLE.Equals(lsCalles.SelectedValue)).Single
            tCalle.Text = _Calle.NOMBRE
            Debug.Print("_callesList.count " + _CallesList.Count.ToString)
            Debug.Print("_Calle.NOMBRE " + _Calle.NOMBRE)
        End If
    End Sub

    ' Private Sub tNumero_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tNumero.TextChanged
    'If tNumero.TextLength > 0 And Not IsNothing(_ClientesList) Then
    '    Debug.Print("antes _ClientesList.Count: " + _ClientesList.Count.ToString)

    '    Dim autoComplete As New AutoCompleteStringCollection
    '    Dim clientesList As New List(Of Entities.CLIENTES)

    '    clientesList = _ClientesList.Where(Function(c) c.NUMERO.Contains(tNumero.Text.Trim)).ToList

    '    Debug.Print("despues _ClientesList.Count: " + clientesList.Count.ToString)

    '    For Each cli As Entities.CLIENTES In _ClientesList
    '        autoComplete.Add(cli.NUMERO)
    '    Next
    '    Try
    '        If autoComplete.Count > 0 Then
    '            tNumero.AutoCompleteMode = AutoCompleteMode.Suggest
    '            tNumero.AutoCompleteSource = AutoCompleteSource.CustomSource
    '            tNumero.AutoCompleteCustomSource = autoComplete
    '        End If

    '    Catch ex As Exception
    '        Debug.Print("tNumero_TextChanged: " + ex.Message)
    '    End Try

    'End If
    ' End Sub

    Private Sub tCalle_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tCalle.TextChanged
        If tCalle.TextLength > 0 Then
            lsCalles.SelectedIndex = lsCalles.FindString(tCalle.Text.Trim)
        End If
    End Sub

#End Region

    Private Sub tNumero_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles tNumero.LostFocus
        If tNumero.TextLength > 0 Then
            _Cliente = ClienteBL.SearchByDireccion(tNumero.Text.Trim, lsCalles.SelectedValue)
            cargarCliente()
        End If
    End Sub

    Private Sub bEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bEliminar.Click
        If Not IsNothing(_Cliente) Then
            If ClienteBL.Delete(_Cliente.CLIENTE) Then
                Util.Mensaje("Cliente Eliminado Correctamente")
                TituloGrid()
            Else
                Util.MensajeError("Error al Elimiar Cliente")
            End If
            Limpiar()
        End If
    End Sub

    Private Sub tFiltro_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tFiltro.TextChanged
        Dim listaFiltro As New List(Of ClientesP)
        Dim filtro As String = tFiltro.Text.Trim
        If filtro.Length = 0 Then
            TituloGrid()
        Else
            Dim query = _ClientesP.Where(Function(p) p.Nombre.Contains(filtro) Or
                                                    p.Calle.Contains(filtro) Or
                                                     p.Numero.Contains(filtro) Or
                                                     p.Fono.Contains(filtro) Or
                                                    p.Rut.Contains(filtro) Or
                                                    p.Villa.Contains(filtro)).ToList

            For Each rec In query
                listaFiltro.Add(rec)
            Next

            gClientes.DataSource = listaFiltro
        End If
       
    End Sub

   
    Private Sub cVillas_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cVillas.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tCalle_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tCalle.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tNumero_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tNumero.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tRut_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tRut.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tNombre_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tNombre.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tFono_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tFono.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tFiltro_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tFiltro.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub
End Class